package com.evil.activiti.listener;

import com.alibaba.fastjson.JSON;
import com.evil.activiti.enums.EventTypeEnum;
import com.evil.activiti.util.ActivityUtil;
import com.evil.application.api.RemoteApplicationOrderNodeService;
import com.evil.application.pojo.dto.order.node.HandleOrderNodeReqDTO;
import com.evil.common.account.dto.user.UserEnterpriseDTO;
import com.evil.common.activiti.enums.HandleTypeEnum;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.SequenceFlow;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 流程拒绝监听器
 *
 * @author 15587
 * @date 2022-08-08 00:00
 */
@Slf4j
@Component("TaskRefuseListener")
@AllArgsConstructor
public class TaskRefuseListener implements ExecutionListener {

    private final RemoteApplicationOrderNodeService remoteApplicationOrderNodeService;

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public void notify(DelegateExecution execution) {
        String eventName = execution.getEventName();
        FlowElement flowElement = execution.getCurrentFlowElement();
        Map<String, Object> variables = execution.getVariables();
        log.info("【流程拒绝监听器】，execution.getEventName参数：{}", eventName);
        log.info("【流程拒绝监听器】，节点id：{}, 节点name:{}", flowElement.getId(), flowElement.getName());
        log.info("【流程拒绝监听器】，execution.getVariables参数：{}", JSON.toJSONString(variables));

        // 执行事件
        if (EventTypeEnum.TAKE.getEvent().equals(eventName)) {
            if (flowElement instanceof SequenceFlow) {
                SequenceFlow sequenceFlow = (SequenceFlow) flowElement;

                // 覆盖订单节点数据
                HandleOrderNodeReqDTO handleOrderNodeReqDTO = new HandleOrderNodeReqDTO();
                handleOrderNodeReqDTO.setHandleType(HandleTypeEnum.REJECTED.getId());
                // 订单id
                Long orderId = execution.getVariable(ActivityUtil.getProcessOrderIdKey(), Long.class);
                handleOrderNodeReqDTO.setOrderId(orderId);
                // 节点id
                long nodeId = Math.abs(ActivityUtil.restoreFlowNodeId(sequenceFlow.getSourceRef()));
                handleOrderNodeReqDTO.setNodeId(nodeId);
                // 处理人（当前登陆人）
                UserEnterpriseDTO assignee = ActivityUtil.getUserEnterpriseByActivitiLoginUser();
                handleOrderNodeReqDTO.setHandlerId(assignee.getUserId());
                // 备注
                String remark = execution.getVariable(ActivityUtil.REMARK, String.class);
                handleOrderNodeReqDTO.setRemark(remark);
                remoteApplicationOrderNodeService.refuseOrderNode(handleOrderNodeReqDTO);
            }
        }
    }
}
